package com.zuul.component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;

@Component
public class ZuulFilterPre extends ZuulFilter {
    private static Logger logger = LoggerFactory.getLogger(ZuulFilter.class);
    @Override
    /** 过滤类型 */
    public String filterType(){
      return   FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder(){
        return 0;
    }

    @Override
    /** 是否开启过滤*/
    public boolean shouldFilter(){
        return true;
    }

    @Override
    public Object run(){
        /** 获取当前请求上下文 */
        RequestContext ctx = RequestContext.getCurrentContext();
        /** 获取到请求参数*/
        HttpServletRequest request = ctx.getRequest();
        Object accessToken = request.getParameter("token");
        if(accessToken == null){
            logger.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(400);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){
                return null;
            }
        }
        logger.info("ok");
        return null;
    }
}
